// author: cjp // createTime: 2021-11-26 10:00 // lastEditTime: 2021-11-29 13:16
<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never" class="mycard">
        <div slot="header" class="clearfix">
          <span>{{ id ? '试题修改' : '试题录入' }}</span>
        </div>
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <!-- 学科 -->
          <el-form-item label="学科" prop="subjectID">
            <el-select v-model="addForm.subjectID" placeholder="请选择学科" class="w400">
              <el-option :label="item.label" v-for="item in subList" :key="item.value" :value="item.value"></el-option>
            </el-select>
          </el-form-item>

          <!-- 目录 -->
          <el-form-item label="目录" prop="catalogID">
            <el-select v-model="addForm.catalogID" placeholder="请选择目录" class="w400">
              <el-option
                v-for="item in dirList"
                :key="item.id"
                :label="item.directoryName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <!-- 企业 -->
          <el-form-item label="企业" prop="enterpriseID">
            <el-select v-model="addForm.enterpriseID" placeholder="请选择企业" class="w400">
              <el-option v-for="item in companyList" :key="item.id" :label="item.company" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <!-- 城市 -->
          <el-form-item label="城市" required>
            <el-col :span="4">
              <el-form-item prop="province" class="w200">
                <el-select v-model="addForm.province" placeholder="请选择省份">
                  <el-option v-for="(item, index) in provinceList" :key="index" :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="4" class="city">
              <el-form-item prop="city">
                <el-select v-model="addForm.city" placeholder="请选择城市">
                  <el-option v-for="(item, index) in cityList" :key="index" :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-form-item>

          <!-- 方向 -->
          <el-form-item label="方向" prop="direction">
            <el-select v-model="addForm.direction" placeholder="请选择方向" class="w400">
              <el-option v-for="(item, index) in directionList" :key="index" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>

          <!-- 题型 -->
          <el-form-item label="题型" prop="questionType">
            <el-radio-group v-model="addForm.questionType">
              <el-radio label="1">单选</el-radio>
              <el-radio label="2">多选</el-radio>
              <el-radio label="3">简答</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 难度 -->
          <el-form-item label="难度" prop="difficulty">
            <el-radio-group v-model="addForm.difficulty">
              <el-radio label="1">简单</el-radio>
              <el-radio label="2">一般</el-radio>
              <el-radio label="3">困难</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 题干 -->
          <el-form-item label="题干" prop="question">
            <quill-editor
              v-model="addForm.question"
              @change="changeQuillEditor"
              @blur="blurQuillEditor"
              :options="editorOption"
              ref="myQuillEditor"
            ></quill-editor>
          </el-form-item>

          <!-- 选项 -->
          <el-form-item label="选项" size="mini" v-if="addForm.questionType !== '3'">
            <!-- 单选按钮组 -->

            <template v-for="(item, index) in addForm.options">
              <div @click="getIndex(index)" :key="index" class="options" v-if="addForm.questionType === '1'">
                <input
                  ref="ipt"
                  type="radio"
                  name="options"
                  v-model="addForm.options[index].isRight"
                  :value="true"
                  @change="change(index)"
                />
                {{ String.fromCharCode(65 + index) }}
                <el-input size="medium" class="ipt" v-model="addForm.options[index].title"></el-input>
                <div class="upload">
                  <el-upload
                    class="avatar-uploader"
                    :http-request="httpRequest"
                    action="#"
                    :show-file-list="false"
                    :before-upload="beforeUpload"
                  >
                    <img v-if="addForm.options[index].img" :src="addForm.options[index].img" class="avatar" />
                    <i v-else class="avatar-uploader-icon">上传图片</i>
                  </el-upload>
                  <i @click="getIndex(index), removeImg()" class="el-icon-close close"></i>
                </div>
                <!-- 存对应的blob地址 -->
                <input type="text" hidden v-model="addForm.options[index].img" />
                <el-button type="primary" @click.prevent="remove(item)">删除选项</el-button>
              </div>
            </template>

            <!-- 多选按钮组 -->
            <template v-for="(item, index) in addForm.options">
              <div @click="getIndex(index)" :key="index" class="options" v-if="addForm.questionType === '2'">
                <input ref="ipt" type="checkbox" v-model="addForm.options[index].isRight" :value="true" />
                {{ String.fromCharCode(65 + index) }}
                <el-input size="medium" class="ipt" v-model="addForm.options[index].title"></el-input>
                <div class="upload">
                  <el-upload
                    class="avatar-uploader"
                    :http-request="httpRequest"
                    action="#"
                    :show-file-list="false"
                    :before-upload="beforeUpload"
                  >
                    <img v-if="addForm.options[index].img" :src="addForm.options[index].img" class="avatar" />
                    <i v-else class="avatar-uploader-icon">上传图片</i>
                  </el-upload>
                  <i @click="getIndex(index), removeImg()" class="el-icon-close close"></i>
                </div>
                <!-- 存对应的blob地址 -->
                <input type="text" hidden v-model="addForm.options[index].img" />
                <el-button type="primary" @click.prevent="remove(item)">删除选项</el-button>
              </div>
            </template>
          </el-form-item>

          <!-- 增加选项按钮 -->
          <el-form-item v-if="addForm.questionType !== '3'">
            <el-button
              :disabled="addForm.questionType === '1'"
              type="danger"
              icon="el-icon-plus"
              size="mini"
              @click="add"
              >增加选项与答案</el-button
            >
          </el-form-item>

          <!-- 解析视频 -->
          <el-form-item label="解析视频" class="w400">
            <el-input v-model="addForm.videoURL" placeholder="请输入视频地址"></el-input>
          </el-form-item>

          <!-- 答案解析 -->
          <el-form-item label="答案解析" prop="answer">
            <quill-editor
              v-model="addForm.answer"
              @blur="$refs.addFormRef.validateField('answer')"
              @change="$refs.addFormRef.validateField('answer')"
              :options="editorOption"
              ref="myQuillEditor"
            ></quill-editor>
          </el-form-item>

          <!-- 题目备注 -->
          <el-form-item label="题目备注" class="w400">
            <el-input type="textarea" v-model="addForm.remarks" :autosize="{ minRows: 4, maxRows: 8 }"></el-input>
          </el-form-item>

          <!-- 试题标签 -->
          <el-form-item label="试题标签" class="w400">
            <el-select multiple v-model="addForm.tags" placeholder="请选择试题标签" class="sel">
              <el-option
                v-for="(item, index) in tagsList"
                :key="index"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>

          <!-- 提交按钮 -->
          <el-form-item>
            <el-button type="primary" @click="submit">{{ id ? '确认修改' : '确认上传' }}</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getCity, getProvince } from '@/module-hmmm/city/index.js'
import { mapGetters, mapActions } from 'vuex'
import { add, detail, update } from '@/api/hmmm/questions.js'
export default {
  name: 'ques-new',
  computed: {
    ...mapGetters(['subList', 'companyList', 'dirList', 'tagsList'])
  },
  watch: {
    // 监听数据变化动态联动下拉框
    'addForm.subjectID': {
      handler() {
        this.initDir({ subjectID: this.addForm.subjectID })
        this.initTags({ subjectID: this.addForm.subjectID })
      },
      deep: true
    },
    'addForm.province': {
      handler() {
        // 小问题here
        // this.addForm.city = ''
        this.cityList = getCity(this.addForm.province)
      },
      deep: true
    }
  },
  data() {
    return {
      // 方向列表
      directionList: ['o2o', '外包服务', '企业服务', '互联网金融', '企业咨询', '互联网', '电子商务', '其他'],
      provinceList: [],
      cityList: [],
      // 请求体数据
      addForm: {
        name: '',
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        options: [],
        question: '',
        videoURL: '',
        answer: '',
        remarks: '',
        tags: ''
      },
      // 表单校验规则
      addFormRules: {
        subjectID: [{ required: true, message: '学科不能为空', trigger: 'change' }],
        catalogID: [{ required: true, message: '目录不能为空', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '企业不能为空', trigger: 'change' }],
        province: [{ required: true, message: '省份不能为空', trigger: 'change' }],
        direction: [{ required: true, message: '方向不能为空', trigger: 'change' }],
        questionType: [{ required: true, message: '题型不能为空', trigger: 'checked' }],
        difficulty: [{ required: true, message: '难度不能为空', trigger: 'checked' }],
        question: [
          { required: true, message: '题干不能为空' },
          { max: 200, message: '请输入200位以内的字符' }
        ],
        answer: [
          { required: true, message: '题干不能为空' },
          { max: 200, message: '请输入200位以内的字符' }
        ]
      },
      // 索引
      index: '',
      // 编辑器选项
      editorOption: {
        placeholder: ''
      },
      // 获取传过来的id
      id: this.$route.query.id
    }
  },
  methods: {
    ...mapActions({
      initSub: 'questionsNew/initSubList',
      initDir: 'questionsNew/initDirList',
      initCompany: 'questionsNew/initCompanyList',
      initTags: 'questionsNew/initTagsList'
    }),
    // 提交数据
    submit() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // tags数组变字符串
        this.addForm.tags = this.addForm.tags.join(',')
        // 判断有没有传过来id
        try {
          this.id ? await update(this.addForm) : await add(this.addForm)
        } catch (error) {
          console.log(error)
        }
        // 弹框
        this.$message.success(this.id ? '试题修改成功！' : '试题录入成功！')
        // 重置校验
        this.$refs.addFormRef.resetFields()
        // 清空数据
        this.addForm = {
          name: '',
          subjectID: '',
          catalogID: '',
          enterpriseID: '',
          province: '',
          city: '',
          direction: '',
          questionType: '1',
          difficulty: '1',
          options: [],
          question: '',
          videoURL: '',
          answer: '',
          remarks: '',
          tags: ''
        }
        // 跳回之前的页面
        this.id ? this.$router.back() : this.$router.push('/questions/list')
      })
    },
    // 初始化省份
    initPro() {
      this.provinceList = getProvince()
    },
    // 循环选项
    circleOptions() {
      for (let i = 0; i < 4; i++) {
        const code = String.fromCharCode(65 + i)
        this.addForm.options.push({ isRight: false, code, title: '', img: '' })
      }
    },
    // 添加选项
    add() {
      const length = this.addForm.options.length
      const code = String.fromCharCode(65 + length)
      this.addForm.options.push({ isRight: false, code, title: '', img: '' })
    },
    // 移除选项
    remove(item) {
      const index = this.addForm.options.indexOf(item)
      if (index !== -1) this.addForm.options.splice(index, 1)
    },
    // 单选框选中让其他isRight设为false、排他
    change(index) {
      const length = this.addForm.options.length
      for (let i = 0; i < length; i++) this.addForm.options[i].isRight = false
      this.addForm.options[index].isRight = true
    },
    // 图片上传之前做一些判断
    beforeUpload(file) {
      // 规定图片大小和图片类型
      const less2M = file.size / 1024 / 1024 < 2
      if (!less2M) {
        this.$message.error('图片大小不能超过 2MB呀！')
      }
      const isType = file.type === 'image/png' || file.type === 'image/jpeg'
      if (!isType) {
        this.$message.error('图片类型只能为 png或者 jpeg呀！')
      }
      return isType && less2M
    },
    // 正式上传，图片预览
    httpRequest(data) {
      this.addForm.options[this.index].img = URL.createObjectURL(data.file)
    },
    // 清空图片
    removeImg() {
      this.addForm.options[this.index].img = ''
    },
    // 获取当前索引
    getIndex(index) {
      this.index = index
    },
    // 富文本校验
    changeQuillEditor() {
      this.$refs.addFormRef.validateField('question')
    },
    // 富文本校验
    blurQuillEditor() {
      this.$refs.addFormRef.validateField('question')
    },
    // 修改时回填的数据
    async getData() {
      if (!this.id) return
      const { data: res } = await detail({ id: this.id })
      this.addForm = res
      // 接收来的tags统一变为数组
      // tags为字符串型,可以为'' , '1' , '1, 2'
      if (res.tags === '') return
      const arr = res.tags.split(',')
      this.addForm.tags = arr
    }
  },
  created() {
    // 均为同步操作，会按照顺序先后执行
    this.initSub()
    this.initCompany()
    this.initPro()
    this.circleOptions()
    // 获取数据回填
    this.getData()
  }
}
</script>

<style lang="scss" scoped>
.mycard {
  .city {
    margin-left: 12px;
  }
  .w200 {
    width: 200px;
  }
  .w400 {
    width: 400px;
  }
  ::v-deep .ql-editor {
    height: 200px !important;
  }
  .options {
    display: flex;
    align-items: center;
    width: 100%;
    margin-bottom: 20px;
  }
  .ipt {
    width: 240px;
    margin-right: 20px;
    margin-left: 10px;
  }
  .upload {
    position: relative;
    .close {
      position: absolute;
      top: -7px;
      right: 0;
      font-size: 14px;
      border: 1px solid #333;
      border-radius: 50%;
      cursor: pointer;
    }
  }
  .avatar-uploader {
    display: inline-block;
    width: 100px;
    height: 60px;
    margin-right: 6px;
    ::v-deep .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      width: 100px;
      height: 60px;
      &:hover {
        border-color: #409eff;
      }
    }
    .avatar-uploader-icon {
      font-size: 14px;
      color: #303133;
      width: 100px;
      height: 60px;
      line-height: 60px;
      text-align: center;
      font-style: normal;
    }
    .avatar {
      width: 100px;
      height: 60px;
      display: block;
      object-fit: cover;
    }
  }
}
</style>
